<template>
  <div>
    <vxe-toolbar>
      <template #buttons>
        <el-button type="success" icon="el-icon-plus" size="medium" @click="insertEvent">新增记录</el-button>
        <!-- <el-button type="success" icon="el-icon-printer" size="medium" @click="printEvent">打印</el-button> -->
        <vxe-input style="float: right;" v-model.trim.lazy="filterName" type="search" placeholder="快捷检索"
          @input="searchEvent"></vxe-input>
      </template>
    </vxe-toolbar>
    <vxe-table resizable ref="XTable" show-overflow border max-height="800" stripe highlight-hover-row highlight-current-row
      :loading="loading" :data="dataList" @sort-change="sortChange">
      <vxe-table-column field="createDate" title="获得日期" sortable></vxe-table-column>
      <vxe-table-column field="sport" title="运动项目" sortable></vxe-table-column>
      <vxe-table-column field="sportItem" title="运动小项" sortable></vxe-table-column>
      <vxe-table-column field="refereeType" title="裁判等级" sortable></vxe-table-column>
      <vxe-table-column field="memo" title="备注" sortable></vxe-table-column>
      <vxe-table-column field="" title="操作" width="110">
        <template #default="{ row,rowIndex }">
          <el-button @click="editEvent(row,rowIndex)" type="success" size="medium" icon="el-icon-edit" circle></el-button>
          <el-button @click="deleteEvent(row)" type="danger" size="medium" icon="el-icon-delete" circle></el-button>
        </template>
      </vxe-table-column>
    </vxe-table>
    <vxe-pager :loading="loading" :current-page="page.currentPage" :page-size="page.pageSize" :total="page.totalResult"
      :layouts="['PrevPage', 'JumpNumber', 'NextPage', 'FullJump', 'Sizes', 'Total']" @page-change="handlePageChange">
    </vxe-pager>
    <vxe-modal v-model="insertModal" title="裁判等级">
      <template #default>
        <el-form inline-message ref="insertForm" :rules="rules" :model="insertForm" label-width="110px">
          <el-form-item label="获得日期" prop="createDate">
            <el-date-picker type="date" placeholder="选择日期" v-model="insertForm.createDate" style="width: 100%;">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="运动项目" prop="sportId">
            <el-select v-model="insertForm.sportId" @change="sportChange" filterable clearable style="width: 100%;"
              placeholder="请选择">
              <el-option :label="item" :value="key" v-for="(item,key,index) in dict_sport" :key="index"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="运动小项">
            <el-select v-model="insertForm.sportItemId" filterable clearable style="width: 100%;" placeholder="请选择">
              <el-option :label="item.name" :value="item.sportItemId" v-for="(item,index) in sportItemData"
                :key="index"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="裁判等级" prop="refereeTypeId">
            <el-select v-model="insertForm.refereeTypeId" filterable clearable style="width: 100%;" placeholder="请选择">
              <el-option :label="item" :value="key" v-for="(item,key,index) in dict_refereeType" :key="index">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="备注" prop="memo">
            <el-input v-model="insertForm.memo"></el-input>
          </el-form-item>
          <el-form-item>
              <el-button type="warning" size="small" @click="insertModal = false">取消</el-button>
              <el-button type="success" size="small" icon="el-icon-s-promotion" @click="insertSave">保存</el-button>
          </el-form-item>
        </el-form>
      </template>
    </vxe-modal>
  </div>
</template>
<script>
  import {person_referee,person_referee_insert,person_referee_update,person_referee_delete,sport_item_by_sportId} from '@/api/person.js'
  import {
    sport_ignoreOrg,
    sport_item,
  } from '@/api/dict.js'
  export default {
    props: ['pId'],
    data() {
      return {
        defaultDataList: [],
        dataList: [],
        page: {
          currentPage: 1,
          pageSize: 10,
          totalResult: 0
        },
        loading: false,
        filterName: '',
        insertModal: false,
        dict_refereeType: {
          1: "国家级裁判",
          2: "一级裁判员",
          3: "二级裁判员",
          4: "三级裁判员",
          5: "国际级裁判",
        },
        dict_sport: {},
        dict_sportItem: {},
        insertForm: {
          createDate: '',
          refereeTypeId: '',
          memo: '',
          sportId: '',
          sportItemId: '',
        },
        sportItemData: [],
        rules: {
          createDate: [{
            required: true,
            message: '这是必填项',
            trigger: 'blur'
          }, ],
          refereeTypeId: [{
            required: true,
            message: '这是必填项',
            trigger: 'blur'
          }, ],
          sportId: [{
            required: true,
            message: '这是必填项',
            trigger: 'blur'
          }, ],
        },
        isInsert: true,
        refereeId: '',
        search: false,
        currentIndex: null,
      }
    },
    created() {
      this.init_dict().then(()=>{
        this.person_referee()
      })
    },
    computed: {
      openDateValid() {
        if (this.insertForm.openDate && this.insertForm.closeDate) {
          if (this.insertForm.openDate > this.insertForm.closeDate) {
            this.$message.error('开始时间必须小于结束时间！')
            return false
          } else {
            return true
          }
        } else {
          return true
        }
      }
    },
    watch: {
      filterName(val) {
    	if(!val){
    	  this.page = {
    	  currentPage: 1,
    	  pageSize: 10,
    	  totalResult: 0,
    	  }
    	  this.search = false
    	  this.findList()
    	}
      }
    },
    methods: {
      deleteEvent(row) {
        this.$confirm('此操作将永久删除该条记录, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          person_referee_delete({pId:this.pId,data:{
            refereeId: row.refereeId
          }}).then(res => {
            if (res.code === 200) {
              this.defaultDataList.forEach((item,index)=>{
              	if(item.refereeId == row.refereeId){
              	  this.defaultDataList.splice(index,1)
              	}
              })
              this.init_data(this.defaultDataList)
              this.findList()
              this.$message.success('删除成功！')
            }
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
      },
      editEvent(row,rowIndex) {
        this.currentIndex = rowIndex
        this.refereeId = row.refereeId
        this.insertForm.sportId = row.sportId+''
        this.sportChange()
        this.insertForm.createDate = row.createDate
        this.insertForm.refereeTypeId = row.refereeTypeId+''
        this.insertForm.memo = row.memo
        this.insertForm.sportItemId = row.sportItemId==0?'':row.sportItemId
        this.isInsert = false
        this.insertModal = true
      },
      insertSave() {
        this.$refs.insertForm.validate((valid) => {
          if (valid && this.openDateValid) {
            let data = {}
            if (this.insertForm.createDate) data.createDate = this.$moment(this.insertForm.createDate).format('YYYY-MM-DD') + ' 00:00:00'
            if (this.insertForm.refereeTypeId) data.refereeTypeId = this.insertForm.refereeTypeId
            if (this.insertForm.memo) data.memo = this.insertForm.memo
            if (this.insertForm.sportId) data.sportId = this.insertForm.sportId
            if (this.insertForm.sportItemId) {
              data.sportItemId = this.insertForm.sportItemId
            }else{
              data.sportItemId = 0
            }
            data.isPlayer = 2
            if (this.isInsert) {
              person_referee_insert({
                pId: this.pId,
                data: data
              }).then(res => {
                if (res.code === 200) {
                  this.dataList.unshift(res.data)
                  this.defaultDataList.push(res.data)
                  this.init_data(this.defaultDataList)
                  this.page.totalResult+=1
                  this.$refs.XTable.setCurrentRow(this.dataList[0])
                  this.$message.success('保存成功')
                  this.insertSuccess = true
                  this.insertModal = false
                } else {
                  this.$message.error(res.message)
                }
              })
            } else {
              data.refereeId = this.refereeId
              person_referee_update({
                pId: this.pId,
                data: data
              }).then(res => {
                if (res.code === 200) {
                  Object.assign(this.dataList[this.currentIndex],res.data)
                  this.defaultDataList.forEach(item=>{
                  	if(res.data.refereeId == item.refereeId){
                  	  Object.assign(item,res.data)
                  	}
                  })
                  this.init_data(this.defaultDataList)
                  this.$message.success('修改成功')
                  this.insertModal = false
                } else {
                  this.$message.error(res.message)
                }
              })
            }
          } else {
            return false;
          }
        })
      },
      insertEvent() {
        this.insertForm = {
          createDate: '',
          refereeTypeId: '',
          memo: '',
          sportId: '',
          sportItemId: '',
        }
        this.isInsert = true
        this.insertModal = true
      },
      sportChange() {
        this.insertForm.sportItemId = ''
        sport_item_by_sportId({
          sportId: this.insertForm.sportId
        }).then(res => {
          if (res.code === 200) {
            this.sportItemData = res.data
          }
        })
      },
      printEvent() {
        let topHtml = '<h2>入职信息</h2>'
        this.searchEvent()
        setTimeout(() => {
          this.$refs.XTable.print({
            sheetName: '入职信息',
            beforePrintMethod: ({
              content
            }) => {
              return topHtml + content
            }
          })
        }, 1000)
      },
      searchEvent() {
        const filterName = this.$XEUtils.toValueString(this.filterName).trim().toLowerCase()
        if (filterName) {
          const filterRE = filterName
          const searchProps = this.searchProps
          const rest = this.defaultDataList.filter(item => searchProps.some(key => this.$XEUtils.toValueString(item[
            key]).toLowerCase().indexOf(filterName) > -1))
          this.dataList = rest.map(row => {
            const item = Object.assign({}, row)
            searchProps.forEach(key => {
              item[key] = this.$XEUtils.toValueString(item[key]).replace(filterRE, match => match)
            })
            return item
          })
          this.page = {
          	currentPage: 1,
          	pageSize: this.dataList.length,
          	totalResult: this.dataList.length
            }
          this.search = true
        } else {
          this.dataList = this.defaultDataList
        }
      },
      person_referee() {
          person_referee(this.pId).then(res => {
            if (res.code === 200 && res.data.length != 0) {
              let data = res.data
              this.init_data(data)
              this.$emit('empRefereeDataPrint',this.defaultDataList)
            } else {
              this.defaultDataList = []
            }
          }).then(() => {
            this.findList()
          })
      },
      init_data(data) {
        if(data.length==0) return
        data.forEach(item => {
          item.createDate = this.$moment(item.createDate).format('YYYY-MM-DD') == 'Invalid date' ? '' : this.$moment(item.createDate).format('YYYY-MM-DD')
          item.refereeType = this.dict_refereeType[item.refereeTypeId]
          item.sport = this.dict_sport[item.sportId]
          item.sportItem = this.dict_sportItem[item.sportItemId]
        })
        this.searchProps = Object.keys(data[0])
        this.defaultDataList = data
      },
      init_dict() {
        return new Promise((resolve, reject) => {
          sport_ignoreOrg().then(res => {
            this.dict_sport = res
            resolve()
          })
          sport_item().then(res => {
            this.dict_sportItem = res
            resolve()
          })
        })
      },
      handlePageChange({
        currentPage,
        pageSize
      }) {
        this.page.currentPage = currentPage
        this.page.pageSize = pageSize
        this.findList()
      },
      sortChange() {
      	if(!this.search){
          this.page.currentPage = 1
      	  this.page.pageSize = this.defaultDataList.length
      	  this.findList()
      	}else{
      	  this.page.pageSize = this.dataList.length
      	}
      },
      findList() {
        this.loading = true
        setTimeout(() => {
          if(this.insertSuccess){
            this.page.totalResult = this.defaultDataList.length
            this.page.currentPage = Math.ceil(this.page.totalResult/this.page.pageSize)
            this.dataList = this.defaultDataList.slice((this.page.currentPage - 1) * this.page
              .pageSize, this.page.currentPage * this.page.pageSize)
            this.$refs.XTable.setCurrentRow(this.dataList[this.dataList.length-1])
            this.insertSuccess = false
          }else{
            this.page.totalResult = this.defaultDataList.length
            this.dataList = this.defaultDataList.slice((this.page.currentPage - 1) * this.page
              .pageSize, this.page.currentPage * this.page.pageSize)
          }
          this.loading = false
        }, 300)
      },
    }
  }
</script>

<style lang="scss" scoped>

</style>
